package com.cinema.servlet;

import java.io.IOException;
import java.security.MessageDigest;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cinema.Bean.User;
import com.cinema.dao.IUserDao;
import com.cinema.dao.imp.UserDaoMysql;

public class UserServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	private IUserDao iUserDao = new UserDaoMysql();

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");

		String method = request.getParameter("method");
		// 用户新增
		if ("add".equals(method)) {
			
			String userId = request.getParameter("userId");
			String userName = request.getParameter("userName");
			String userPwd = getMD5(request.getParameter("userPwd")); 
			String sex = request.getParameter("sex");
			String email = request.getParameter("email");
			String mobile = request.getParameter("mobile");
			double balance = Double.parseDouble(request.getParameter("balance"));
			
			// 设置格式
			Format format = new SimpleDateFormat("yyyy-MM-dd");
			// 获取当前时间
			Date date = new Date();
			
			User u = new User();
			u.setUserId(userId);
			u.setUserName(userName);
			u.setUserPwd(userPwd);
			u.setSex(sex);
			u.setEmail(email);
			u.setMobile(mobile);
			u.setBalance(balance);
			u.setRegisterTime(format.format(date));
			
			int insert = iUserDao.insert(u);
			
			if (insert == 1) {
				response.getWriter().print("success");
				request.getSession().removeAttribute("ulist");
			} else {
				response.getWriter().print("error");
			}
			request.getRequestDispatcher("/login.jsp").forward(request, response);

		} else if ("delete".equals(method)) {
			String userId = request.getParameter("userId");
			if (userId != null && userId != "") {

				User user = new User();
				user.setUserId(userId);

				int delete = iUserDao.delete(user);

				if (delete == 1) {
					response.getWriter().print("success");
					request.getSession().removeAttribute("ulist");
				} else {

					response.getWriter().print("error");
				}
			}
		} else if ("getUser".equals(method)) {
			String userId = request.getParameter("userId");

			if (userId != null && userId != "") {
				User user = iUserDao.SelectById(userId);
				request.setAttribute("user", user);
			}
			request.getRequestDispatcher("/User/edit.jsp").forward(request, response);

		} else if ("update".equals(method)) {
			String userId = request.getParameter("userId");
			String userName = request.getParameter("userName");
			String userPwd = getMD5(request.getParameter("userPwd")); 
			String sex = request.getParameter("sex");
			String email = request.getParameter("email");
			String mobile = request.getParameter("mobile");
			String b = request.getParameter("balance");
			Double balance = Double.parseDouble(b);

			User user = new User(userId, userName, userPwd, sex, email, mobile, balance);
			int update = iUserDao.update(user);
			if (update == 1) {
				request.getSession().removeAttribute("ulist");
			}
			response.sendRedirect("User/index.jsp");
			
		} else if ("updateBalance".equals(method)) { // 根据用户Id修改用户余额
			String userId = request.getParameter("userId");
			String b = request.getParameter("balance");
			Double balance = Double.parseDouble(b);

			User user = new User(userId, balance);
			
			int update = iUserDao.updateByUserId(user);
			
			if (update == 1) {
				response.getWriter().print("success");
				request.getSession().removeAttribute("ulist");
				User u = iUserDao.SelectById(userId);
				request.getSession().setAttribute("loginUser", u);

			} else {
				response.getWriter().print("error");
			}
			
		} else if ("getBalanInfo".equals(method)) { // 根据用户Id获取用户余额
			String userId = request.getParameter("userId");

			if (userId != null && userId != "") {
				User userBalance = iUserDao.SelectById(userId);
				// 将对象转化为json字符串
				String str=JSON.toJSONString(userBalance); 
		        
				//保存信息
				response.getWriter().print(str);
			}

		} else if ("modifyPwd".equals(method)) {  // 根据用户Id修改密码
			// 1.根据id查找对应的用户
			String userId = request.getParameter("userId");
			// 对密码先进行加密，再进行比较
			String oldPwd = getMD5(request.getParameter("oldPwd")); 
			String newPwd = getMD5(request.getParameter("newPwd")); 
			// 通过用户Id查找原密码
			User userInfo = iUserDao.SelectById(userId);
			// 默认修改失败
			int update = 0;
			//2. 密码是否匹配，匹配则修改，不匹配，则返回失败
			if(userInfo!=null && userInfo.getUserPwd().equals(oldPwd)){
				User user = new User(userId, newPwd);
				update = iUserDao.updatePwdByUserId(user);
			}
			//保存信息,修改成功
			if (update == 1) {
				response.getWriter().print("success");
				request.getSession().removeAttribute("ulist");
			} else {
				response.getWriter().print("error");
			}
			
		}  else if ("select".equals(method)) {
			request.getSession().removeAttribute("ulist");
			String keyword = request.getParameter("keyword");

			List<User> users = iUserDao.Select(keyword);
			request.getSession().setAttribute("ulist", users);
		}
	}
	
	/** 
     * 对密码md5加密(大写+数字) 
     * @param str 传入要加密的字符串 
     * @return  MD5加密后的字符串 
     */  
    public static String getMD5(String s) {  
        char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};         
  
        try {  
            byte[] btInput = s.getBytes();  
            // 获得MD5摘要算法的 MessageDigest 对象  
            MessageDigest mdInst = MessageDigest.getInstance("MD5");  
            // 使用指定的字节更新摘要  
            mdInst.update(btInput);  
            // 获得密文  
            byte[] md = mdInst.digest();  
            // 把密文转换成十六进制的字符串形式  
            int j = md.length;  
            char str[] = new char[j * 2];  
            int k = 0;  
            for (int i = 0; i < j; i++) {  
                byte byte0 = md[i];  
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];  
                str[k++] = hexDigits[byte0 & 0xf];  
            }  
            return new String(str);  
        } catch (Exception e) {  
            e.printStackTrace();  
            return null;  
        }  
    }  
}
